<!--  -->
<template>
  <div>
    <div class="infoview">
      <table class="mars-table">
        <tr>
          <td>方式</td>
          <td colspan="2">
            <el-select v-model="value" placeholder="请选择" size="small">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </td>
        </tr>
        <tr>
          <td>起点</td>
          <td>
            <input id="startIpt" type="text" :value="startPos" class="form-control" style="width: 200px" />
          </td>
          <td>
            <el-button type="primary" size="small" @click="drawStartPoint">选点</el-button>
          </td>
        </tr>
        <tr>
          <td>终点：</td>
          <td>
            <input id="endIpt" type="text" :value="endPos" class="form-control" style="width: 200px" />
          </td>
          <td>
            <el-button type="primary" size="small" @click="drawEndPoint">选点</el-button>
            <!-- <input type="button" class="btn btn-primary" value="选点" id="endPoint" @click="drawEndPoint" /> -->
          </td>
        </tr>
        <tr>
          <td></td>
          <td colspan="3">
            <el-button type="primary" size="small" @click="startAnalysis">开始分析</el-button>
            <el-button type="primary" size="small" @click="clear">清除</el-button>

            <!-- <input type="button" class="btn btn-primary" value="开始分析" id="FX" @click="startAnalysis" />
            <input type="button" class="btn btn-primary" value="清除" id="clear" @click="clear" /> -->
          </td>
        </tr>
      </table>
    </div>

    <div class="infoview result" style="top: 250px; display: none; word-break: break-all; width: 300px" v-show="isShowResult">
      总距离：<span id="allDistance" style="color: #cad1d1" v-html="allDistanceHtml"></span><br />
      预计时间：<span id="useTime" style="color: #cad1d1" v-html="useTimeHtml"></span><br />
      导航：<span id="dh" style="color: #cad1d1" v-html="dhHtml"></span><br />
    </div>

    <div id="popupContent" class="marsBlackPanel animation-spaceInDown" v-show="false">
      <div class="marsBlackPanel-text">
        <div style="width: 200px; text-align: left">
          <div>总 距 离：<span id="lblAllLen"> </span></div>
          <div>总 时 间：<span id="lblAllTime"> </span></div>

          <div>剩余时间：<span id="lblRemainTime"> </span></div>
          <div>剩余距离：<span id="lblRemainLen"> </span></div>
        </div>
      </div>
      <span class="mars3d-popup-close-button closeButton">×</span>
    </div>
  </div>
</template>

<script>
// const eventTarget = new this.mars3d.BaseClass()
// const poiLayer = new this.mars3d.layer.GraphicLayer()
export default {
  name: 'RoutePlanning',
  data() {
    return {
      value: '1',
      options: [
        {
          value: '1',
          label: '步行路线查询'
        },
        {
          value: '3',
          label: '驾车路线查询'
        }
      ],
      startPos: '', // 起点经纬度
      endPos: '', // 终点经纬度
      loading: null,
      isShowResult: false,
      useTimeHtml: '',
      allDistanceHtml: '',
      dhHtml: ''
    }
  },
  // 生命周期 - 创建完成（访问当前this实例）
  created() {
    this.routeLayer = new this.mars3d.layer.GraphicLayer()
    this.map.addLayer(this.routeLayer)
  },
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.queryGaodeRoute = new this.mars3d.query.GaodeRoute({
      key: [this.ak.gaode]
    })
  },
  beforeDestroy() {
    this.clear()
    this.routeLayer.remove()
  },
  methods: {
    // 选择起点
    drawStartPoint() {
      if (this.startGraphic) {
        this.startGraphic.remove()
        this.startGraphic = null
      }
      var that = this
      this.map.graphicLayer.startDraw({
        type: 'billboard',
        style: {
          image: 'img/marker/start.png',
          horizontalOrigin: this.Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: this.Cesium.VerticalOrigin.BOTTOM,
          clampToGround: true
        },
        success: function (graphic) {
          that.startGraphic = graphic

          const point = graphic.point
          point.format()
          that.startPos = point.lng + ',' + point.lat
          that.queryRoute()
        }
      })
    },
    // 选择终点
    drawEndPoint() {
      if (this.endGraphic) {
        this.endGraphic.remove()
        this.endGraphic = null
      }
      var that = this
      this.map.graphicLayer.startDraw({
        type: 'billboard',
        style: {
          image: 'img/marker/end.png',
          horizontalOrigin: this.Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: this.Cesium.VerticalOrigin.BOTTOM,
          clampToGround: true
        },
        success: function (graphic) {
          that.endGraphic = graphic

          const point = graphic.point
          point.format()
          that.endPos = point.lng + ',' + point.lat
          that.queryRoute()
        }
      })
    },
    // 开始分析按钮
    startAnalysis() {
      if (!this.startGraphic || !this.endGraphic) {
        this.$message.warning('请设置起点和终点')
      } else {
        this.queryRoute()
      }
    },
    // 清除按钮
    clear() {
      if (this.startGraphic) {
        this.startGraphic.remove()
        this.startGraphic = null
      }
      if (this.endGraphic) {
        this.endGraphic.remove()
        this.endGraphic = null
      }
      this.startPos = ''
      this.endPos = ''

      this.routeLayer.clear()
      this.isShowResult = false
    },
    queryRoute() {
      if (!this.startGraphic || !this.endGraphic) {
        return
      }

      this.routeLayer.clear()

      this.loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      this.isShowResult = false

      const type = Number(this.value) // GaodeRouteType枚举类型

      var that = this
      this.queryGaodeRoute.query({
        type: type,
        points: [this.startGraphic.coordinate, this.endGraphic.coordinate],
        success: function (data) {
          if (that.loading) {
            that.loading.close()
          }

          const lineFirst = data.paths[0]
          const points = lineFirst.points
          if (!points || points.length < 1) {
            return
          }

          const time = that.formatTime(lineFirst.allDuration)
          const distance = that.formatLength(lineFirst.allDistance)
          const html = '<div>总距离：' + distance + '<br/>所需时间：' + time + '</div>'

          const graphic = new that.mars3d.graphic.PolylineEntity({
            positions: points,
            style: {
              clampToGround: true,
              material: that.Cesium.Color.AQUA.withAlpha(0.8),
              width: 5
            },
            popup: html
          })

          let roamLine
          let flydata
          if (that.value === '1') {
            // 步行
            flydata = {
              name: '步行路线',
              speed: 40,
              positions: points,
              model: {
                show: true,
                url: '//data.mars3d.cn/gltf/mars/man/walk.gltf',
                scale: 5,
                minimumPixelSize: 50
              },
              shadow: [
                {
                  type: 'circle',
                  radius: 10,
                  color: '#ffff00',
                  opacity: 0.3,
                  materialType: that.mars3d.MaterialType.CircleWave,
                  speed: 10,
                  count: 3,
                  gradient: 0.1,
                  show: true
                }
              ],
              camera: {
                type: 'gs',
                radius: 500,
                heading: 193,
                pitch: -26
              },
              clockRange: that.Cesium.ClockRange.CLAMPED, // CLAMPED到达终点后停止
              pauseTime: 0.5 // 每个点的停留时长（单位：秒）也支持回调方法。
            }
          } else if (that.value === '3') {
            // 驾车
            flydata = {
              name: '驾车路线',
              speed: 160,
              positions: points,
              // model: {
              //   show: true,
              //   url: '//data.mars3d.cn/gltf/mars/qiche.gltf',
              //   scale: 0.2,
              //   minimumPixelSize: 50,
              // },
              model: {
                url: '//data.mars3d.cn/gltf/mars/jingche/jingche.gltf',
                heading: 90,
                minimumPixelSize: 50,
                show: true
              },
              path: {
                color: '#ffff00',
                width: 3,
                show: true
              },
              camera: {
                type: 'gs',
                radius: 500,
                heading: 193,
                pitch: -26
              },
              interpolation: true // 是否setInterpolationOptions插值
            }
          }

          roamLine = new that.mars3d.graphic.RoamLine(flydata)
          that.routeLayer.addGraphic(roamLine)
          that.routeLayer.addGraphic(graphic)
          // 启动漫游
          roamLine.start()

          that.showResult(data)
        },
        error: function (msg) {
          if (this.loading) {
            this.loading.close()
          }

          window.toastr.error(msg)
        }
      })
    },
    showResult(data) {
      this.isShowResult = true
      const allTime = this.formatTime(data.paths[0].allDuration)
      const allDistance = this.formatLength(data.paths[0].allDistance)

      let dhHtml = ''
      for (let i = 0; i < data.paths[0].steps.length; i++) {
        const item = data.paths[0].steps[i]
        dhHtml += item.instruction + '；'
      }

      this.useTimeHtml = allTime

      this.allDistanceHtml = allDistance
      this.dhHtml = dhHtml
    },
    formatTime(strtime) {
      strtime = Number(strtime) || 0

      if (strtime < 60) {
        return strtime.toFixed(0) + '秒'
      } else if (strtime >= 60 && strtime < 3600) {
        var miao = Math.floor(strtime % 60)
        return Math.floor(strtime / 60) + '分钟' + (miao !== 0 ? miao + '秒' : '')
      } else {
        strtime = Math.floor(strtime / 60) // 秒转分钟
        return Math.floor(strtime / 60) + '小时' + Math.floor(strtime % 60) + '分钟'
      }
    },
    formatLength(val, unit) {
      if (val == null) return ''
      val = Number(val)

      if (unit == null || unit === 'auto') {
        if (val < 1000) {
          unit = 'm'
        } else {
          unit = 'km'
        }
      }

      var valstr = ''
      switch (unit) {
        default:
        case 'm':
          valstr = val.toFixed(2) + '米'
          break
        case 'km':
          valstr = (val * 0.001).toFixed(2) + '公里'
          break
        case 'mile':
          valstr = (val * 0.00054).toFixed(2) + '海里'
          break
        case 'zhang':
          valstr = (val * 0.3).toFixed(2) + '丈'
          break
      }
      return valstr
    }
  }
}
</script>
<style scoped>
/* @import url(); 引入css类 */
.form-control {
  color: #ffffff;
  background-color: rgba(63, 72, 84, 0.7);
  border: none;
}

/**infoview浮动面板*/
.infoview {
  position: absolute;
  top: 70px;
  left: 20px;
  padding: 10px 15px;
  border-radius: 4px;
  border: 1px solid rgba(128, 128, 128, 0.5);
  color: #ffffff;
  background: rgba(0, 0, 0, 0.5);
  /* box-shadow: 0 3px 14px rgba(128, 128, 128, 0.5); */
  z-index: 19870100;
}
.infoview-right {
  left: auto;
  right: 10px;
}

.infoview input,
.infoview textarea {
  color: #ffffff;
  background-color: rgba(32, 160, 255, 0.2);
  border: 1px solid #e4eaec;
  font-size: 14px;
}

.infoview select {
  color: #ffffff;
  border: 1px solid #e4eaec;
  font-size: 14px;
}

.infoview > div {
  margin-top: 5px;
}

.resultview {
  max-width: 500px;
  display: flex;
  text-align: center;
}
.mars-table {
  width: 100%;
  border-collapse: collapse;
  border-spacing: 0;
  margin-top: 5px;
  margin-bottom: 5px;
}

.mars-table tr td {
  padding: 5px 10px;
  text-align: left;
  white-space: nowrap;
}

.mars-table tr td:first-child {
  border-left: none;
}

.mars-table .nametd {
  padding: 5px 20px 5px 10px;
}
</style>
